<?php
/**
 * Created by Error202
 * Date: 22.08.2017
 */

namespace app\core\forms\user;

use app\core\entities\User;
use yii\base\Model;
use Yii;

class ProfileEditForm extends Model
{
    public ?string $username = '';
    public ?string $password = '';
    public ?string $password2 = '';

    public User $_user;

    public function __construct(User $user, $config = [])
    {
        $this->username = $user->username;
        $this->_user = $user;
        parent::__construct($config);
    }

    public function rules(): array
    {
        return [
            ['username', 'required'],
	        [['username'], 'trim'],
            [['password', 'password2'], 'string', 'max' => 32, 'min' => 3, 'tooShort' => 'Password must contain at least {min} characters', 'tooLong' => 'Maximum password length {max} characters'],
            ['password2', 'compare', 'compareAttribute'=>'password', 'skipOnEmpty' => false, 'message' => "Passwords don't match"],
	        ['username', 'string', 'min' => 2, 'max' => 32],
            ['password' , 'checkPassword'],
        ];
    }

    public function checkPassword($attribute, $params)
    {
        if ($this->password && strcspn($this->password, '0123456789') == strlen($this->password)) {
            $this->addError($attribute, 'Password must contain numbers');
        }

        if ($this->password && ctype_alnum($this->password)) {
            $this->addError($attribute, 'Password must contain special characters, ex.: !?#$@ etc. ');
        }
    }
}
